<template>
    <div class="container">
        <!-- 回到顶部 -->
        <div class="nav">
            <el-row>
                <el-select v-model="searchStatus" placeholder="请输入广告状态">
                    <el-option v-for="item in adStatysMap" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>

                <el-select v-model="searchType" placeholder="请输入广告类型">
                    <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>

                <el-button type="primary" @click="search()" icon="Search">查找</el-button>
                <el-button type="primary" icon="Plus" @click="handleCreate()">添加</el-button>
            </el-row>
        </div>
        <div class="table">
            <el-table :data="tableData" style="width: 100%;" border max-height="700">
                <el-table-column prop="id" label="广告ID" align="center" />
                <el-table-column prop="title" label="广告标题" width="200" align="center" />
                <el-table-column prop="imgUrl" label="广告图片" width="100" align="center">
                    <template #default="scope">
                        <div class="pic">
                            <el-popover v-if="scope.row.imgUrl && scope.row.imgUrl != USELESS_PIC" placement="right"
                                :width="400" trigger="click">
                                <template #reference>
                                    <img :src="scope.row.imgUrl" alt="">
                                </template>
                                <template #default>
                                    <div class="popoverImg">
                                        <img :src="scope.row.imgUrl" alt="">
                                    </div>
                                </template>
                            </el-popover>
                            <el-tag v-else type="info">类型无需图片</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="广告类型" align="center">
                    <template #default="scope">
                        <el-tag>{{ scope.row.type == 1 ? "轮播" : scope.row.type == 2 ? "分类精选" : scope.row.type == 3 ?
                            "横幅" : scope.row.type == 4 ? "首页轮播下5按钮" : scope.row.type == 6 ? "公告"
                                : "商品推荐" }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="广告状态" align="center">
                    <template #default="scope">
                        <el-tag type="success">{{ scope.row.status ? '激活' : '冻结' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="unionType" label="关联类型" align="center">
                    <template #default="scope">
                        <el-tag type="warning">{{ scope.row.unionType == 1 ? "商品" : scope.row.unionType == 2 ? "类目" :
                            scope.row.unionType == 3
                                ? "关键字" : "功能页面" }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
                <el-table-column prop="gmtCreate" label="创建时间" align="center">
                    <template #default="scope">
                        {{ new Date(scope.row.gmtCreate).friendTime() }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="170" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="Pagination">
            <Pagination :data="pagination" @setlm="getlm" @setpg="getpg"></Pagination>
        </div>

        <!-- 删除对话框 -->
        <el-dialog v-model="deleterDialogVisible" title="警告" width="25%" style="height:200px" align-center>
            <span>确定要删除？</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="deleterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmDelete()">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 新增对话框 -->
        <el-dialog v-model="createDialogVisible" :title="createDialogTitle" @close="cancelCreate()" width="600px"
            style="padding: 20px;" align-center>
            <div class="create">
                <el-form :model="createData" ref="ruleFormRef" :rules="rules">
                    <el-form-item label="广告标题" :label-width="formLabelWidth" prop="title">
                        <el-input v-model="createData.title" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="广告类型" prop="type" :label-width="formLabelWidth">
                        <el-select v-model="createData.type" :placeholder="adTypeMap[0].name">
                            <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <div class="atverPic" :style="{ backgroundColor: 'rgba' + createData.color }"
                        v-if="createData.type && createData.type != 6 && createData.type != 9">
                        <el-form-item label="广告图片" :label-width="formLabelWidth">
                            <el-upload class="avatar-uploader" :headers="headers" :action="uploadPath"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <!-- 画布 -->
                                <div v-if="createData.imgUrl" class="canvasBox">
                                    <canvas id="canvas"></canvas>
                                </div>
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </div>
                    <el-form-item label="广告状态" prop="status" :label-width="formLabelWidth">
                        <el-switch v-model="status" />
                    </el-form-item>
                    <el-form-item label="关联类型" prop="unionType" :label-width="formLabelWidth">
                        <el-select v-model="createData.unionType" :placeholder='!createData.type ? "请先选择广告类型" : "点击时跳转目标"'
                            :disabled="!createData.type">
                            <el-option v-for="item in adUnionTypeMap" :key="item.value" :label="item.name"
                                :value="item.value"
                                :disabled="createData.type == 2 && createData.type != item.value || createData.type == 9 && createData.type != item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品" prop="unionValue" v-if="createData.unionType == 9"
                        :label-width="formLabelWidth">
                        <el-cascader v-model="createData.unionValue" :options="productCategoryData"
                            :props="{ emitPath: false, value: 'id', }" @change="handleChange" />
                    </el-form-item>
                    <el-form-item label="类目" prop="unionValue" v-else-if="createData.unionType == 2"
                        :label-width="formLabelWidth">
                        <el-cascader :props="{ emitPath: false, value: 'id', children: 'childrenList', label: 'title' }"
                            v-model="createData.unionValue" :options="cascaderCategoryData" @change="handleChange" />
                    </el-form-item>
                    <el-form-item label="关键字" prop="unionValue" v-else-if="createData.unionType == 3"
                        :label-width="formLabelWidth">
                        <el-input v-model="createData.unionValue" placeholder="点击广告后，用户将得到'此关键字'的商品搜索 " />
                    </el-form-item>
                    <el-form-item label="功能页面" prop="unionValue" v-else-if="createData.unionType == 4"
                        :label-width="formLabelWidth">
                        <el-select v-model="createData.unionValue" placeholder="请选择一个功能页面">
                            <el-option v-for="item in functionPages" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelCreate()">取消</el-button>
                    <el-button type="primary" @click="confirmCreate(ruleFormRef)">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
    
<script setup lang="ts">
import type { IBackStatus } from "#/index";
import { ClassAdvert } from "#/index";

import { get, post, uploadPath } from '@/utils/https'
// import themeColor from '@/utils/colorExtraction';
import { onMounted, reactive, ref, computed, watch } from 'vue'
import Pagination from '../../components/Pagination/Pagination.vue'//分页组件
import { ElMessage } from 'element-plus/lib/components/index.js';
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus/lib/components/form/index.js'
import type { UploadProps } from 'element-plus'
import cookie from "js-cookie";

const USELESS_PIC = ref("https://www.baidu.com/img/flexble/logo/pc/result.png")

const handleChange = (value: any) => {
    console.log(value)
}

/**
 * 数据
 * @pages 最大页数
 * @tableData 初始化数据 表格数据
 * @pagination 分页绑定数据
 * @searchStatus 类型查找
 * @searchType 广告状态查找
 * @deleterDialogVisible 删除对话框
 */
// 请求头
const headers = computed(() => {
    return {
        ADMINTOKEN: cookie.get("token")
    }
})


let pages = computed(() => Math.ceil(pagination.count / pagination.limit))
let tableData: TypeAdver[] = reactive([])
let cascaderCategoryData = reactive([])
let productCategoryData = reactive([])
let pagination = reactive({
    page: 1,
    limit: 10,
    count: 0
})
let deleteData = reactive({
    type: undefined,
    adId: undefined,
})
//创建接口传递的参数
let createData = reactive(new ClassAdvert())
let adId = ref()
let status = ref(false)
let searchStatus = ref('')
let searchType = ref('')
const deleterDialogVisible = ref(false)
const createDialogVisible = ref(false)
let createDialogTitle = ref('创建')

const formLabelWidth = '80px'

// 6种广告类型
const adTypeMap = reactive([
    { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: "轮播" },
    { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
    { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: "横幅" },
    { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: "首页轮播图下5按钮" },
    { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: "公告" },
    { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" }
]);
// 4种广告关联类型
const adUnionTypeMap = reactive([
    { value: 9, name: "商品" },
    { value: 2, name: "类目" },
    { value: 3, name: "关键字" },
    { value: 4, name: "功能页面" }
]);
// 广告状态
const adStatysMap = reactive([
    { value: 0, name: "冻结" },
    { value: 1, name: "激活" }
]);
// 功能页面
const functionPages = reactive([
    { value: "/pages/product/groupshop", name: "团购列表" },
    { value: "/pages/coupon/list", name: "优惠劵列表" }
])



//———————事件——————— 

// 表单验证
const ruleFormRef = ref<FormInstance>()//表单验证
const rules = reactive<FormRules>({
    title: [{ required: true, message: '广告标题不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    unionType: [{ required: true, message: '关联类型不能为空', trigger: 'change' }],
    unionValue: [{ required: true, message: '关联值不能为空', trigger: 'change' }],
})

/**
 *  handleEdit 点击编辑
 */

const handleEdit = (row: any) => {
    createDialogTitle.value = '编辑'
    adId.value = row.id
    if (1 === row.unionType || 2 === row.unionType) {
        row.unionValue = +row.unionValue
    }
    Object.assign(createData, row)
    if (createData.status) {
        status.value = true
    } else {
        status.value = false
    }
    if (6 == createData.type || 9 == createData.type) {
        createData.imgUrl = USELESS_PIC.value
        createData.color = ''
    } else (
        canvas(createData.imgUrl)
    )
    createDialogVisible.value = true
}
// 取消 （清空表单
const cancelCreate = () => {
    ruleFormRef.value!.resetFields()
    createDialogVisible.value = false
}
/**
 * 点击创建 handleCreate 
 * 确认创建/编辑 confirmCreate
 */
const handleCreate = () => {
    // Object.assign(createData, new ClassAdvert())//赋值为初始值
    createDialogTitle.value = '创建'
    createDialogVisible.value = true
}


const confirmCreate = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: any) => {
        if (valid) {
            if (6 == createData.type || 9 == createData.type) {
                createData.imgUrl = USELESS_PIC.value
                createData.color = ''
            }
            if (createDialogTitle.value == '创建') {
                if (status.value) {
                    createData.status = 1
                } else {
                    createData.status = 0
                }
                let data = {
                    _gp: 'admin.advert',
                    _mt: 'create',
                    ...createData
                }
                // console.log(data);
                post(data).then((res: any) => {
                    // console.log('添加', res)
                    let { errno, errmsg } = res
                    if (200 == errno) {
                        ElMessage.success(errmsg)
                        createDialogVisible.value = false
                        getInit()
                    } else {
                        ElMessage.error(errmsg)
                    }
                }).catch(err => {
                    createDialogVisible.value = false
                })
            } else {
                let data = {
                    _gp: 'admin.advert',
                    _mt: 'edit',
                    adId: adId.value,
                    ...createData
                }
                // console.log(data, 'edit');
                post(data).then((res: any) => {
                    // console.log('编辑', res)
                    let { errno, errmsg } = res
                    if (200 == errno) {
                        ElMessage.success(errmsg)
                        createDialogVisible.value = false
                        getInit()
                    } else {
                        ElMessage.error(errmsg)
                    }
                }).catch(err => {
                    createDialogVisible.value = false
                })
            }

        } else {
            console.log('请填写信息!')
            return false
        }
    })
}


/**
 * 广告图片
 * @beforeAvatarUpload	上传文件之前的钩子
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片类型必须是JPG或者PNG!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

/**
 * 广告图片
 * @handleAvatarSuccess 文件上传成功时的钩子
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response: any,
    uploadFile: any
) => {
    // console.log(response, 'response');
    createData.imgUrl = response.url
    canvas(response.url)
}
// 画布绘制图片
const canvas = (url: string) => {
    const img = new Image()
    img.src = url
    img.setAttribute("crossOrigin", "anonymous")
    // 获取之后执行
    setTimeout(() => {
        var canvas = document.getElementById("canvas") as HTMLCanvasElement;
        let context = canvas.getContext('2d') as any
        context.clearRect(0, 0, canvas.width, canvas.height)//重绘
        createData.color = '(255,255,255,255)'//重新赋值（绘制失败显示空白 白色
        context?.drawImage(img, 0, 0, 148, 148)
        let data = context.getImageData(0, 0, img.width, img.height).data || []//获取图片的第一个点的颜色
        createData.color = '(' + data[0] + ',' + data[1] + ',' + data[2] + ',' + data[3] + ')'
        // console.log(bgcolor.value, 'color');
    }, 50)
}

//监听广告类型发生变化关联类型响应数据
watch(() => createData.type, (values, oldValues) => {
    if (createData.type == 2) {
        createData.unionType = 2
    } else if (createData.type == 9) {
        createData.unionType = 9
    }
})

/**
 * @handleDelete 点击删除
 * @param row 点击行数据
 */
const handleDelete = (row: any) => {
    deleterDialogVisible.value = true
    // console.log(row, 'row');
    deleteData.adId = row.id
    deleteData.type = row.type
}
/**
 * @confirmDelete 点击确认删除
 */
const confirmDelete = () => {
    let data = {
        _gp: 'admin.advert',
        _mt: 'delete',
        adId: deleteData.adId,
        type: deleteData.type,
    }
    post(data).then((res: any) => {
        console.log('删除成功', res)
        let { errno, errmsg } = res
        if (200 == errno) {
            ElMessage.success(errmsg)
            getInit()
        } else {
            ElMessage.error(errmsg)
        }
        deleterDialogVisible.value = false
    }).catch(err => {
        deleterDialogVisible.value = false
    })
}

/**
 * @search 查找
 */
function search() {
    getInit()
}

/**
 * 分页自定义事件
 */
const getlm = (v: IBackStatus) => {
    pagination.limit = v.backStatus
}
const getpg = (v: IBackStatus) => {
    pagination.page = v.backStatus
}

// 解决分页请求两次问题
watch([() => pagination.limit, () => pagination.page], (values, oldValues) => {
    if (pagination.page <= pages.value) {
        console.log(213);
        getInit()
    }
})
// 获取初始化数据
let getInit = () => {
    let data = {
        _gp: 'admin.advert',
        _mt: 'list',
        pageNo: pagination.page,
        limit: pagination.limit,
        type: searchType.value,
        status: searchStatus.value,
    }
    // console.log(data, 'data');

    get(data).then((res) => {
        console.log('广告列表获取数据成功', res)
        tableData.length = 0
        tableData.push(...res.data.items)
        pagination.count = res.data.count
    })

    let productData = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree',
    }
    get(productData).then((res: any) => {
        // console.log('产品获取数据成功', res)
        if (200 == res.errno) {
            productCategoryData.length = 0
            productCategoryData = res.data
        }
    })
    let categoryData = {
        _gp: 'admin.category',
        _mt: 'categoryTree',
    }
    get(categoryData).then((res: any) => {
        // console.log('类目获取数据成功', res)
        if (200 == res.errno) {
            cascaderCategoryData.length = 0
            cascaderCategoryData = res.data
        }
    })

}
onMounted(() => {
    getInit()
})

</script> 
    
<style lang="less" scoped>
.el-row {
    margin-bottom: 10px;
    width: 1200px;
    height: 32px;
    // overflow: hidden;
}

.popoverImg {
    overflow: hidden;
}

.popoverImg img {
    width: 100%;
    height: 100%;
}

/**广告图片 */
.atverPic {
    width: 400px;
    // overflow: hidden;
    height: 155px;
}

.canvasBox {
    margin-left: 50px;
    border: 1px dashed black;
    width: 148px;
    height: 148px;
    padding: 2px;
}


.avatar-uploader .avatar {
    width: 148px;
    height: 148px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    border: #acaaaa dashed 1px;
    text-align: center;
}
</style>